/* eslint-disable guard-for-in */
/* eslint-disable no-plusplus */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-unused-expressions */
/* eslint-disable array-callback-return */
/* eslint-disable eqeqeq */
import React from 'react';
import { cloneDeep } from 'lodash';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Spin,
  Select,
  message,
  Steps,
  Input,
  Radio,
  Row,
  Col,
  InputNumber,
} from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { urlParse } from '@/utils/utils';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';

const { Option } = Select;
const FormItem = Form.Item;
const { Step } = Steps;

@connect(({ quoupdate, loading }) => ({
  loading: loading.models.quoupdate,
  customerNameList: quoupdate.customerNameList,
  suppReplaceCorpId: quoupdate.suppReplaceCorpId, // 当前角色所在角色
  supplyList: quoupdate.supplyList, // 签约方
  contList: quoupdate.contList, //  商务合同
  supplyContList: quoupdate.supplyContList, // 供应商合同
  productData: quoupdate.productData, // 产品列表
  updateDetailData: quoupdate.updateDetailData, // 修改前查看
  method: quoupdate.method, // 报价方式
  taxes: quoupdate.taxes, // 是否含税
  subUpdateDetailData: quoupdate.subUpdateDetailData,
  originalData: quoupdate.originalData,
  quoupdate,
  suppList: quoupdate.suppList,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dictData: { SER_TYPE: [], POS_WAY: [], YES_NO_FLAG: [], QUO_TYPE: [] },
      comType: null, // 公司类型
      productDataall: [], // 打包产品数据
      childproarr: [],
      quoId: '',
      quoState: '',
    };
  }

  componentDidMount() {
    const {
      dispatch,
      form,
      location,
      updateDetailData,
      suppReplaceCorpId,
      quoupdate: { isGoBack = false },
    } = this.props;
    // 请求字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['SER_TYPE', 'POS_WAY', 'YES_NO_FLAG', 'QUO_TYPE'],
    }).then(data => {
      this.setState({ dictData: data });
    });

    const contInfo = urlParse(decodeURI(location.search));
    // 返回来的
    if (!isGoBack) {
      dispatch({
        type: 'quoupdate/updateModelData',
        payload: {
          updateDetailData: {},
          formFieldsValue: {},
          customerNameList: [],
          suppReplaceCorpId: '',
          supplyList: [],
          custId: '',
          contList: [],
          supplyContList: [],
          productData: [],
          taxes: '1', // 是否含税
          method: '2', // 报价方式
          subUpdateDetailData: {}, // 提交时用的数据
        },
      });
    }
    this.setState({
      quoId: contInfo.quoId,
      quoState: contInfo.quoState,
    });
    // eslint-disable-next-line no-unused-expressions
    contInfo && this.setState({ ...contInfo });

    // 获取所有产品
    this.getAllProducts();
    if (!isGoBack) {
      // 第一次进来
      this.initializationData();
    } else {
      // 下一步返回进来
      // eslint-disable-next-line no-lonely-if
      if (updateDetailData.suppList) {
        // 没有刷新
        dispatch({
          type: 'quoupdate/clearUpdateValue',
          payload: { suppList: updateDetailData.suppList },
        });
        this.selectProducts(updateDetailData.allProductId);
        if (updateDetailData.suppId === suppReplaceCorpId) {
          this.setState({ comType: '1' });
          this.getCustomers(updateDetailData.suppId); // 本地  请求客户名称
        } else {
          this.setState({ comType: '2' }, () => {
            form.setFieldsValue({ serType: '1' });
          });
          this.getSupplyers(updateDetailData.suppId); // 全国 请求供应商合同
          this.selectSupply(updateDetailData.custContId);
        }
      } else {
        // 刷新页面了
        this.initializationData();
      }
    }
  }

  // 初始数据
  initializationData = () => {
    const { dispatch, form, location, updateDetailData } = this.props;
    // 请求字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['SER_TYPE', 'POS_WAY', 'YES_NO_FLAG', 'QUO_TYPE'],
    }).then(data => {
      this.setState({ dictData: data });
    });
    const contInfo = urlParse(decodeURI(location.search));
    // 获取当前角色所在公司对应的平台供应商
    dispatch({
      type: 'quoupdate/getPlaSuppData',
      payload: {},
      callback: res => {
        if (res.success && res.data) {
          // 签约方(供应商)列表
          dispatch({
            type: 'quoupdate/getListByUserData',
            payload: { name: null, status: '2' },
            callback: response => {
              if (response.success && response.data.length) {
                if (contInfo.comType && contInfo.comType == '2') {
                  // 供应商合同入口：全国
                  response.data.forEach(item => {
                    if (item.suppId == contInfo.suppId) {
                      form.setFieldsValue({ suppId: updateDetailData.suppId || item.suppId });
                      this.getSupplyers(updateDetailData.suppId || item.suppId, () => {
                        form.setFieldsValue({ custContId: contInfo.contId });
                        // 根据选择的供应商合同：请求客户名称
                        dispatch({
                          type: 'quoupdate/getsuppContData',
                          payload: { contId: contInfo.contId },
                          callback: resData => {
                            if (resData.success && resData.data.length) {
                              form.setFieldsValue({
                                custId: resData.data[0].custId,
                              });
                            } else {
                              message.warning('该供应商合同下无客户！');
                            }
                          },
                        });
                      });
                    }
                  });
                  form.setFieldsValue({ serType: '1' });
                } else if (contInfo.comType && contInfo.comType == '1') {
                  // 商务合同入口：本地
                  form.setFieldsValue({ suppId: updateDetailData.suppId || res.data[0].suppId });
                  const customerNameList = [];
                  const contList = [];
                  dispatch({
                    type: 'quoupdate/getInfoData',
                    payload: { custId: contInfo.custId },
                    callback: resData => {
                      if (resData.success && resData.data.length) {
                        customerNameList.push({
                          custId: contInfo.custId,
                          name: contInfo.custName,
                        });
                        contList.push({
                          contId: contInfo.contId,
                          contName: contInfo.contName,
                        });
                        dispatch({
                          type: 'quoupdate/updateModelData',
                          payload: { customerNameList, contList },
                        });
                        form.setFieldsValue({
                          custId: contInfo.custId,
                          custContId: contInfo.contId,
                          serType: contInfo.serType,
                        });
                      } else {
                        message.warning(`${res.message || '暂无数据！'}`);
                      }
                    },
                  });
                }
              }
            },
          });
        } else {
          message.warning(res.message || '服务端未知错误');
        }
        // 修改前查看详情
        dispatch({
          type: 'quoupdate/updateDetail',
          payload: { quoId: contInfo.quoId },
          callback: resdata => {
            if (resdata.suppId === res.data[0].suppId) {
              this.setState({ comType: '1' });
              this.getCustomers(resdata.suppId); // 本地  请求客户名称
            } else {
              this.setState({ comType: '2' }, () => {
                form.setFieldsValue({ serType: '1' });
              });
              this.getSupplyers(resdata.suppId); // 全国 请求供应商合同
              this.selectSupply(resdata.custContId);
            }
            const newsuppList = [];
            // eslint-disable-next-line no-unused-expressions
            resdata &&
              resdata.listQuoPd &&
              resdata.listQuoPd.map((i, k) => {
                const selectpd = [];
                i.listQuoPd.map(it => {
                  selectpd.push(it.pdId);
                });

                newsuppList.push({
                  id: k,
                  listQuoPd: '',
                  selectpd,
                });
              });
            dispatch({
              type: 'quoupdate/clearUpdateValue',
              payload: { suppList: newsuppList },
            });
            this.selectCustomers(resdata.custId);
            this.selectProducts(resdata.allProductId);
          },
        });
      },
    });
  };

  // 签约方选择 : 根据选择显示不同
  selectCompany = (value, o) => {
    const { suppReplaceCorpId, dispatch, form } = this.props;
    form.resetFields(['custId', 'custContId', 'serType']);
    dispatch({
      type: 'quoupdate/clearInitialValue',
      payload: {},
    });
    if (o.props.suppid === suppReplaceCorpId) {
      this.setState({ comType: '1' });
      this.getCustomers(value); // 本地  请求客户名称
    } else {
      this.setState({ comType: '2' }, () => {
        form.setFieldsValue({ serType: '1' });
      });
      this.getSupplyers(value); // 全国 请求供应商合同
    }
  };

  // 选择签约方为本地：请求客户名称
  getCustomers = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'quoupdate/getCustomersData',
      payload: {},
    });
  };

  // 选择客户名称：请求商务合同
  selectCustomers = custId => {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'quoupdate/updateModelData',
      payload: { supplyContList: [] },
    });
    dispatch({
      type: 'quoupdate/getByCustIdData',
      payload: { custId },
      callback: res => {
        if (!res.success && !res.data.length) {
          message.warning('该客户名称下暂无商务合同！');
        }
        form.resetFields(['custContId', 'serType']);
      },
    });
  };

  // 选择客户名称
  clearCustContId = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'quoupdate/clearInitialValue',
      payload: {},
    });
  };

  // 选择商务合同:设置服务类型
  selectCont = custContId => {
    const { dictData } = this.state;
    const { contList, form, dispatch } = this.props;
    contList.forEach(custCont => {
      if (custCont.contId == custContId) {
        dictData.SER_TYPE.forEach(serverType => {
          if (custCont.serType == serverType.itemCode) {
            dispatch({
              type: 'quoupdate/changeSerType',
              payload: { serType: serverType.itemCode },
            });
            form.setFieldsValue({ serType: serverType.itemCode });
          }
        });
      }
    });
  };

  // 根据签约方为全国：请求供应商合同
  getSupplyers = suppId => {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'quoupdate/updateModelData',
      payload: { customerNameList: [] },
    });
    dispatch({
      type: 'quoupdate/getsuppIdData',
      payload: { suppId },
      callback: res => {
        if (!res.success && !res.data.length) {
          message.warning('暂无供应商合同列表');
        }
        form.resetFields(['custId', 'custContId']);
      },
    });
  };

  // 根据选择的供应商合同：请求客户名称
  selectSupply = (contId, options, e) => {
    const { dispatch, form } = this.props;
    if (options && options.props && options.props.state && options.props.state == 3) {
      message.warning('该供应商合同已到期！');
    }
    dispatch({
      type: 'quoupdate/getsuppContData',
      payload: { contId },
      callback: () => {
        form.resetFields(['custId']);
      },
    });
    if (e === true) {
      dispatch({
        type: 'quoupdate/clearCustId',
        payload: {},
      });
    }
  };

  // 获取产品列表
  getAllProducts = () => {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'quoupdate/getProductData',
      payload: {},
      callback: res => {
        form.resetFields(['custId']);
        if (!res.success) {
          message.error(`获取产品类型失败,请重试!`);
        }
      },
    });
  };

  // 是否含税
  changeTaxes = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'quoupdate/updateModelData',
      payload: { taxes: e.target.value },
    });
  };

  // 报价方式
  changeMethod = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'quoupdate/updateModelData',
      payload: { method: e.target.value },
    });
    dispatch({
      type: 'quoupdate/clearUpdateValue',
      payload: {
        suppList: [
          {
            // 打包产品列表
            id: new Date().getTime(),
            listQuoPd: '',
          },
        ],
      },
    });
  };

  // 添加分组
  addList = () => {
    const { suppList, dispatch } = this.props;
    const newData = suppList && suppList.map(item => ({ ...item }));
    newData.push({
      id: new Date().getTime(),
      listQuoPd: '',
      selectpd: [],
    });

    dispatch({
      type: 'quoupdate/clearUpdateValue',
      payload: { suppList: newData },
    });
  };

  // 删除分组
  deleteContact = currentIndex => {
    const { suppList, dispatch } = this.props;
    const newData = suppList.map(item => ({ ...item })); // 删除其中一条数据
    const newSuppList = [];
    newData.map(item => {
      if (item.id !== currentIndex) {
        newSuppList.push(item);
      }
    });
    dispatch({
      type: 'quoupdate/clearUpdateValue',
      payload: { suppList: newSuppList },
    });
  };

  // 选择产品
  selectProducts = proArr => {
    const { productData, suppList, dispatch, form } = this.props;
    const newData = productData && productData.map(item => ({ ...item }));
    const newProductDate = [];
    newData &&
      newData.map(item => {
        proArr &&
          proArr.map(itm => {
            if (item.pdId === itm) {
              newProductDate.push(item);
            }
          });
      });
    const suppIdList = [];
    suppList &&
      suppList.length > 0 &&
      suppList.map((sitem, sindex) => {
        const arr3 = [];
        if (sitem && sitem.selectpd && sitem.selectpd.length) {
          // eslint-disable-next-line no-plusplus
          for (let i = 0; i < sitem.selectpd.length; i++) {
            if (proArr.indexOf(sitem.selectpd[i]) > -1) {
              arr3.push(sitem.selectpd[i]);
            }
            // else {
            //   // 如果匹配不到 没有产品下拉
            //   arr3.push(proArr[sindex]);
            // }
          }
        }
        form.setFieldsValue({ [`listQuoPd_${sindex}`]: arr3 });
        suppIdList.push({
          selectpd: arr3,
          id: sindex,
          listQuoPd: '',
        });
      });

    this.setState({ productDataall: newProductDate });
    dispatch({
      type: 'quoupdate/clearUpdateValue',
      payload: { suppList: suppIdList },
    });
  };

  // 打包产品
  changeBundleone = proArr => {
    const { dispatch } = this.props;
    dispatch({
      type: 'quoupdate/clearUpdateValue',
      payload: {
        suppList: proArr,
      },
    });
  };

  // 子打包产品
  changeBundle = (proArr, id) => {
    const { childproarr } = this.state;
    const { dispatch, suppList } = this.props;
    const arraypro = [];
    const temp = [];
    proArr.map(item => {
      arraypro.push(item);
      childproarr.push(item);
    });
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < childproarr.length; i++) {
      if (temp.indexOf(childproarr[i]) == -1) {
        temp.push(childproarr[i]);
      }
    }
    // eslint-disable-next-line no-plusplus
    for (let j = 0; j < arraypro.length; j++) {
      if (temp.indexOf(arraypro[j]) == -1) {
        temp.push(arraypro[j]);
      }
    }
    this.setState({
      childproarr,
    });
    suppList.map(items => {
      if (items.id === id) {
        // eslint-disable-next-line no-param-reassign
        items.selectpd = proArr;
      }
    });
    dispatch({
      type: 'quoupdate/clearUpdateValue',
      payload: {
        suppList,
      },
    });
  };

  // 匹配产品id与显示中文
  matchPdIdOrName = (allProductList, pdIdOrName, callback) => {
    let newPdIdOrName = pdIdOrName;
    allProductList.forEach(p => {
      if (
        pdIdOrName.toUpperCase?.().indexOf?.('PDINF_') > -1 ||
        pdIdOrName.toUpperCase?.().indexOf?.('PDEFINED_') > -1
      ) {
        // 存在id
        newPdIdOrName = pdIdOrName;
      } else if (p.pdName === pdIdOrName) {
        newPdIdOrName = p.pdId;
      }
    });
    callback && callback(newPdIdOrName);
  };

  // 下一步
  nextStep = () => {
    const {
      method,
      form,
      updateDetailData,
      dispatch,
      subUpdateDetailData,
      originalData,
      suppList,
    } = this.props;
    const { quoId, quoState } = this.state;
    // eslint-disable-next-line consistent-return
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let packList = [];
        let packArray = []; // 选中的打包产品
        const { pdId } = values;
        const newPdId = [];
        pdId.map(itm => {
          this.matchPdIdOrName(updateDetailData.allProductList, itm, p => {
            newPdId.push(p);
          });
        });
        suppList.map((item, index) => {
          const formPdIdOrName = values[`listQuoPd_${item.id}`];
          //  1不打包，2部分打包，3全部打包
          if (method == '1') {
            pdId.map(itm => {
              this.matchPdIdOrName(updateDetailData.allProductList, itm, p => {
                packList.push({
                  listQuoPd: [p],
                });
              });
            });
          } else if (method == '3') {
            packList.push({
              listQuoPd: newPdId,
            });
          } else if (method == '2') {
            item.selectpd = [];
            for (const j in formPdIdOrName) {
              // 去匹配id和名称
              this.matchPdIdOrName(updateDetailData.allProductList, formPdIdOrName[j], p => {
                packArray.push({
                  listQuoPd: p,
                });
                item.selectpd.push(p);
              });
            }
            packList.push({
              listQuoPd: item.selectpd,
            });
          }
        });
        if (method == '2') {
          // 选择打包产品时，将剩余的产品放在一个包中
          // eslint-disable-next-line prefer-spread
          const packArrays = [].concat.apply([], packArray);
          const packArraysList = [];
          packArrays.map((itess, indess) => {
            packArraysList.push(itess.listQuoPd);
          });

          const newPacks = newPdId.filter(i => packArraysList.indexOf(i) == -1); // 筛选有没有不选择的产品
          if (newPacks.length) {
            // 如果有，放进一个包里面
            // packList = [];
            newPacks.forEach(item => {
              packList.push({
                listQuoPd: [item],
              });
            });
          }
        }
        if (packList.length > 0) {
          // 转格式listQuoPd:[{paid:'1'},{pdid:'2'}]

          packList.map(item => {
            let newObject = {};
            const newPackList = [];
            if (item.listQuoPd) {
              item.listQuoPd.map(itm => {
                newObject = {
                  pdId: itm,
                };
                newPackList.push(newObject);
              });
              // eslint-disable-next-line no-param-reassign
              item.listQuoPd = newPackList;
            }
          });
        } else {
          packList = [];
        }
        let submitData = {}; // 组装参数
        submitData = {
          suppId: values.suppId,
          custId: values.custId,
          custContId: values.custContId,
          serType: values.serType,
          taxFlag: values.taxFlag,
          taxRatio: values.taxRatio,
          quoName: values.quoName,
          quoType: updateDetailData.quoType || updateDetailData.quoType,
          pdId: newPdId,
          packList,
        };
        if (submitData.quoType == 2) {
          const zpacList = [];
          const newplacList = [];
          packList.map(itempack => {
            zpacList.push(itempack.listQuoPd);
          });
          zpacList.map(letitem => {
            letitem.map(itemlast => {
              newplacList.push(itemlast.pdId);
            });
          });
          const temp = {};
          const r = [];
          const len = newplacList.length;
          let val;
          let type;
          // eslint-disable-next-line no-plusplus
          for (let i = 0; i < len; i++) {
            val = newplacList[i];
            type = typeof val;
            if (!temp[val]) {
              temp[val] = [type];
              r.push(val);
            } else {
              return message.warning('不能选择重复的产品');
            }
          }
        }
        submitData.detailPackList = subUpdateDetailData.packList;

        submitData.detailListQuoPd = subUpdateDetailData.listQuoPd;
        subUpdateDetailData.suppId = values.suppId;
        subUpdateDetailData.custContId = values.custContId;
        subUpdateDetailData.custId = values.custId;
        // 点击下一步，保存当前页的数据
        updateDetailData.quoName = values.quoName;
        updateDetailData.taxRatio = values.taxRatio;
        updateDetailData.allProductId = values.pdId;
        suppList.map(suitem => {
          // eslint-disable-next-line no-useless-concat
          const newid = `${'listQuoPd' + '_'}${suitem.id}`;
          // eslint-disable-next-line no-param-reassign
          suitem.newid = newid;
        });
        // eslint-disable-next-line guard-for-in
        for (const iv in values) {
          suppList.map(suppitem => {
            if (iv == suppitem.newid) {
              // eslint-disable-next-line no-param-reassign
              suppitem.selectpd = values[iv];
            }
          });
        }
        updateDetailData.suppList = suppList;
        const newDetailPackList = [];
        submitData.detailPackList.map((deitem, deindex) => {
          deitem.listQuoPd.map(lquoitem => {
            // eslint-disable-next-line no-param-reassign
            lquoitem.onlyKey = deindex;
            newDetailPackList.push(lquoitem);
          });
        });
        submitData.packList.map((pckitem, pckindex) => {
          const newDePackItem = [];
          pckitem.listQuoPd.map(laitem => {
            newDetailPackList.map(nditem => {
              if (laitem.pdId == nditem.pdId) {
                newDePackItem.push(nditem);
              }
            });
          });
          // 包增加了有变化 / 包内有变化
          if (submitData.packList.length > submitData.detailPackList.length) {
            for (
              let i = 0;
              i < submitData.packList.length - submitData.detailPackList.length;
              // eslint-disable-next-line no-plusplus
              i++
            ) {
              const itemObj = {
                listAttr: [],
                listInfo: [],
                listQuoPd: [],
                priceList: [
                  {
                    areaId: '', // 执行地区
                    suggPrice: '0', //	建议售价
                    quotePrice: '', // 报价金额
                    taxMoney: '', // 税金
                    id: i,
                  },
                ],
              };
              submitData.detailPackList.push(itemObj);
            }
          }
          submitData.detailPackList[pckindex].listQuoPd = newDePackItem;
        });
        const originalList = [];
        const lassubIndex = [];
        // 目前的产品
        submitData.packList.map(pckitem => {
          const packQunList = [];
          pckitem.listQuoPd.map(plitem => {
            packQunList.push(plitem.pdId);
          });
          lassubIndex.push({
            selectpd: packQunList,
          });
        });
        submitData.detailPackList.map(sditem => {
          // eslint-disable-next-line no-param-reassign
          sditem.pdList = [];
          sditem.listQuoPd.map(liitme => {
            sditem.pdList.push(liitme.pdId);
          });
        });
        submitData.pdList = lassubIndex;
        // 组装原有的产品
        originalData.listQuoPd.map(lilitem => {
          const paList = [];
          lilitem.listQuoPd.map(liiten => {
            paList.push(liiten.pdId);
          });
          originalList.push({
            selectpd: paList,
          });
        });
        const identicalPd = []; // 相同的产品包
        submitData.pdList.map(ypditem => {
          originalList.map(ozitem => {
            if (ypditem.selectpd.sort().toString() == ozitem.selectpd.sort().toString()) {
              identicalPd.push(ypditem);
            }
          });
        });
        if (identicalPd.length > 0) {
          submitData.detailPackList.map(ditem => {
            identicalPd.map(iditem => {
              if (iditem.selectpd.sort().toString() == ditem.pdList.sort().toString()) {
                // eslint-disable-next-line no-param-reassign
                ditem.isChange = 2;
              }
            });
          });
        } else {
          submitData.detailPackList.map((dtitem, dtindex) => {
            // eslint-disable-next-line no-param-reassign
            dtitem.priceList = [
              {
                areaId: '', // 执行地区
                suggPrice: '0', //	建议售价
                quotePrice: '', // 报价金额
                taxMoney: '', // 税金
                id: dtindex,
              },
            ];
          });
        }
        submitData.detailPackList.map((lsitem, lsiindex) => {
          // eslint-disable-next-line no-empty
          if (lsitem.isChange && lsitem.isChange === 2) {
          } else {
            // eslint-disable-next-line no-param-reassign
            lsitem.priceList = [
              {
                areaId: '', // 执行地区
                suggPrice: '0', //	建议售价
                quotePrice: '', // 报价金额
                taxMoney: '', // 税金
                id: lsiindex,
              },
            ];
          }
        });

        // 不打包 - 去重
        if (submitData.quoType == 1) {
          const removalDetailPackList = [];
          const removalPackList = [];
          const removalPdList = [];
          const obj = {};
          const packObj = {};
          const pdListObj = {};
          for (let u = 0; u < submitData.detailPackList.length; u++) {
            if (!obj[submitData.detailPackList[u].pdList[0]]) {
              removalDetailPackList.push(submitData.detailPackList[u]);
              obj[submitData.detailPackList[u].pdList[0]] = true;
            }
          }
          for (let l = 0; l < submitData.pdList.length; l++) {
            if (!pdListObj[submitData.pdList[l].selectpd[0]]) {
              removalPdList.push(submitData.pdList[l]);
              pdListObj[submitData.pdList[l].selectpd[0]] = true;
            }
          }
          for (let p = 0; p < submitData.packList.length; p++) {
            if (!packObj[submitData.packList[p].listQuoPd[0].pdId]) {
              removalPackList.push(submitData.packList[p]);
              packObj[submitData.packList[p].listQuoPd[0].pdId] = true;
            }
          }

          submitData.packList = removalPackList;
          submitData.detailPackList = removalDetailPackList;
          submitData.pdList = removalPdList;
        }
        submitData.vno = subUpdateDetailData.vno;
        submitData.allProductList = updateDetailData.allProductList;

        try {
          // 解决之前的详情价格处理有bug，处理钩子
          // 切换到下一页前对详情价格做查询，复制对象进入
          /**
           * listQuoPd: Array(4)
              0:
              listAttr: []
              listInfo: []
              listQuoPd: [{…}]
              priceList: [{…}]
           */
          submitData.detailPackList = submitData.detailPackList.map(detailPackItem => {
            // 从详情数据中找到对应的数据
            const findPickItem = updateDetailData.listQuoPd.find(
              pack => pack.listQuoPd[0].pdId === detailPackItem.listQuoPd[0].pdId
            );
            const temp = cloneDeep(detailPackItem);
            // 找到了复制价格
            if (findPickItem) {
              temp.priceList = cloneDeep(findPickItem.priceList);
            }
            return temp;
          });
        } catch (e) {
          console.error(e);
        }
        window.localStorage.setItem('quotationadd', JSON.stringify(submitData));
        dispatch({
          type: 'quoupdate/updateModelData',
          payload: { nextData: submitData },
        });
        router.push(`/salemanage/quotation/updatesetprice?quoId=${quoId}&quoState=${quoState}`);
      }
    });
  };

  render() {
    const { comType, dictData, productDataall } = this.state;
    const {
      productData,
      supplyContList,
      contList,
      supplyList,
      customerNameList,
      loading,
      updateDetailData,
      taxes,
      method,
      suppList,
      form,
    } = this.props;
    const newaa = suppList;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 9 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 7 },
      },
    };
    const formItemLayouts = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 11 },
        md: { span: 11 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 12 },
      },
    };
    const Test = () => (
      <span style={{ display: 'inline-block', width: 200 }}>请输入小数点不超过3位的数字</span>
    );

    // 字典下拉
    const dictOL = dictList =>
      dictList &&
      dictList.map(options => <Option key={options.itemCode}>{options.itemName}</Option>);
    const SelelctCust = () => {
      if (comType && comType === '1') {
        return (
          <div>
            {updateDetailData.quoState === 1 ? (
              <div>
                <FormItem {...formItemLayout} label="客户名称">
                  {getFieldDecorator('custId', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: updateDetailData.custId,
                  })(
                    <HOCSelect
                      placeholder="请选择"
                      onSelect={this.selectCustomers}
                      showSearch
                      optionFilterProp="children"
                      onChange={this.clearCustContId}
                    >
                      {customerNameList &&
                        customerNameList.map(one => (
                          <Option key={one.custId} value={one.custId}>
                            {one.name}
                          </Option>
                        ))}
                    </HOCSelect>
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="商务合同">
                  {getFieldDecorator('custContId', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: updateDetailData.custContId,
                  })(
                    <HOCSelect
                      placeholder="请选择"
                      showSearch
                      optionFilterProp="children"
                      onSelect={(value, options) => this.selectCont(value, options)}
                    >
                      {contList &&
                        contList.map(one => (
                          <Option key={one.contId} value={one.contId}>
                            {one.contName}
                          </Option>
                        ))}
                    </HOCSelect>
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="服务类型">
                  {getFieldDecorator('serType', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue:
                      updateDetailData &&
                      updateDetailData.serType &&
                      updateDetailData.serType.toString(),
                  })(
                    <HOCSelect
                      placeholder="请输入关键字检索"
                      showSearch
                      optionFilterProp="children"
                      disabled
                    >
                      {dictOL(dictData.SER_TYPE)}
                    </HOCSelect>
                  )}
                </FormItem>
              </div>
            ) : (
              <div>
                <FormItem {...formItemLayout} label="客户名称">
                  {getFieldDecorator('custId', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: updateDetailData.custId,
                  })(<span>{updateDetailData.custName}</span>)}
                </FormItem>
                <FormItem {...formItemLayout} label="商务合同">
                  {getFieldDecorator('custContId', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: updateDetailData.custContId,
                  })(<span>{updateDetailData.contName}</span>)}
                </FormItem>
                <FormItem {...formItemLayout} label="服务类型">
                  {getFieldDecorator('serType', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue:
                      updateDetailData &&
                      updateDetailData.serType &&
                      updateDetailData.serType.toString(),
                  })(<span>{updateDetailData.serTypeName}</span>)}
                </FormItem>
              </div>
            )}
          </div>
        );
      }
      if (comType && comType !== '1') {
        return (
          <div>
            {updateDetailData.quoState === 1 ? (
              <div>
                <FormItem {...formItemLayout} label="供应商合同">
                  {getFieldDecorator('custContId', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: updateDetailData.custContId,
                  })(
                    <Select
                      placeholder="请选择"
                      onSelect={(value, options) => this.selectSupply(value, options, true)}
                      showSearch
                      optionFilterProp="children"
                    >
                      {supplyContList &&
                        supplyContList.map(one => (
                          <Option key={one.contId} value={one.contId}>
                            {one.contName}
                          </Option>
                        ))}
                    </Select>
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="客户名称">
                  {getFieldDecorator('custId', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: updateDetailData.custId,
                  })(
                    <Select
                      placeholder="请选择"
                      onSelect={this.selectSuppCust}
                      showSearch
                      optionFilterProp="children"
                    >
                      {customerNameList &&
                        customerNameList.map(one => (
                          <Option key={one.custId} value={one.custId}>
                            {one.name}
                          </Option>
                        ))}
                    </Select>
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="服务类型">
                  {getFieldDecorator('serType', {
                    rules: [{ required: false, message: '请选择' }],
                    initialValue:
                      updateDetailData &&
                      updateDetailData.serType &&
                      updateDetailData.serType.toString(),
                  })(
                    <Select
                      placeholder="请输入关键字检索"
                      showSearch
                      optionFilterProp="children"
                      disabled
                    >
                      {dictOL(dictData.SER_TYPE)}
                    </Select>
                  )}
                </FormItem>
              </div>
            ) : (
              <div>
                <FormItem {...formItemLayout} label="供应商合同">
                  {getFieldDecorator('custContId', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: updateDetailData.custContId,
                  })(<span>{updateDetailData.contName}</span>)}
                </FormItem>
                <FormItem {...formItemLayout} label="客户名称">
                  {getFieldDecorator('custId', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: updateDetailData.custId,
                  })(<span>{updateDetailData.custName}</span>)}
                </FormItem>
                <FormItem {...formItemLayout} label="服务类型">
                  {getFieldDecorator('serType', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue:
                      updateDetailData &&
                      updateDetailData.serType &&
                      updateDetailData.serType.toString(),
                  })(<span>{updateDetailData.serTypeName}</span>)}
                </FormItem>
              </div>
            )}
          </div>
        );
      }
      return null;
    };
    return (
      <Form>
        <PageHeaderWrapper wrapperClassName={styles.advancedForm}>
          <Spin tip="Loading..." spinning={loading}>
            <Card>
              <Steps current={0} style={{ marginBottom: 70 }}>
                <Step title="选择产品" />
                <Step title="设置价格" />
                {updateDetailData.quoState === 1 ? null : <Step title="人员信息" />}
                <Step title="完成" />
              </Steps>
              {updateDetailData.quoState === 1 ? (
                <FormItem {...formItemLayout} label="签约方">
                  {getFieldDecorator('suppId', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: updateDetailData.suppId,
                  })(
                    <Select
                      placeholder="请选择"
                      onSelect={this.selectCompany}
                      showSearch
                      optionFilterProp="children"
                    >
                      {supplyList &&
                        supplyList.map(one => (
                          <Option key={one.suppId} value={one.suppId} suppid={one.suppId}>
                            {one.name}
                          </Option>
                        ))}
                    </Select>
                  )}
                </FormItem>
              ) : (
                <FormItem {...formItemLayout} label="签约方">
                  {getFieldDecorator('suppId', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: updateDetailData.suppId,
                  })(<span>{updateDetailData.suppName}</span>)}
                </FormItem>
              )}

              <SelelctCust />
              <FormItem {...formItemLayout} label="报价单名称">
                {getFieldDecorator('quoName', {
                  rules: [{ required: true, message: '请输入' }],
                  initialValue: updateDetailData.quoName,
                })(<Input placeholder="请输入" maxLength={100} />)}
              </FormItem>
              <FormItem {...formItemLayout} label="选择产品">
                {getFieldDecorator('pdId', {
                  rules: [{ required: true, message: '请选择' }],
                  initialValue: updateDetailData.allProductId,
                })(
                  <Select onChange={this.selectProducts} placeholder="请选择" mode="multiple">
                    {productData &&
                      productData.map(one => (
                        <Option key={one.pdId} value={one.pdId} datas={one}>
                          {one.pdName}
                        </Option>
                      ))}
                  </Select>
                )}
              </FormItem>
              <Row gutter={24} style={{ marginLeft: 0, marginRight: '-25px' }}>
                <Col span={6} offset={6} style={{ position: 'relative' }}>
                  <FormItem {...formItemLayouts} label="是否含税报价">
                    {getFieldDecorator('taxFlag', {
                      initialValue: taxes,
                      rules: [{ required: false, message: '请选择' }],
                    })(
                      <Radio.Group onChange={this.changeTaxes}>
                        {dictData &&
                          dictData.YES_NO_FLAG &&
                          dictData.YES_NO_FLAG.map(options => (
                            <Radio key={options.itemCode} value={options.itemCode}>
                              {options.itemName}
                            </Radio>
                          ))}
                      </Radio.Group>
                    )}
                  </FormItem>
                  <Col span={5} style={{ position: 'absolute', top: 0, right: 0 }}>
                    {taxes === '2' ? (
                      <FormItem>
                        {getFieldDecorator('taxRatio', {
                          rules: [
                            {
                              required: true,
                              message: <Test />,
                              pattern: /^-?\d+\.?\d{0,3}$/,
                            },
                          ],
                          initialValue: updateDetailData.taxRatio || '0.001',
                        })(
                          <InputNumber
                            placeholder="填写税率"
                            min={0.001}
                            max={100}
                            style={{ width: 100 }}
                            formatter={value => `${value}%`}
                            parser={value => value.replace('%', '')}
                          />
                        )}
                      </FormItem>
                    ) : null}
                  </Col>
                </Col>
              </Row>

              {updateDetailData.quoState === 1 ? (
                <FormItem {...formItemLayout} label="报价方式">
                  {getFieldDecorator('quoType', {
                    initialValue: method,
                    rules: [{ required: false, message: '请选择' }],
                  })(
                    <Radio.Group onChange={this.changeMethod}>
                      {dictData.QUO_TYPE.sort((a, b) => a.itemCode - b.itemCode).map(options => (
                        <Radio key={options.itemCode} value={options.itemCode}>
                          {options.itemName}
                        </Radio>
                      ))}
                    </Radio.Group>
                  )}
                </FormItem>
              ) : (
                <FormItem {...formItemLayout} label="报价方式">
                  {getFieldDecorator('quoType', {
                    rules: [{ required: false, message: '请选择' }],
                  })(<span>{updateDetailData.quoTypeName}</span>)}
                </FormItem>
              )}
              {method === '2' ? (
                <div>
                  {newaa &&
                    newaa.map((item, index) => (
                      <Row key={item.id}>
                        <Col span={12} offset={6}>
                          <FormItem wrapperCol={{ md: { span: 14, offset: 6 } }} key={item.id}>
                            {getFieldDecorator(`listQuoPd_${item.id}`, {
                              rules: [{ required: true, message: '请选择' }],
                              initialValue: item.selectpd,
                            })(
                              <Select
                                onChange={value => {
                                  this.changeBundle(value, item.id);
                                }}
                                placeholder="请选择"
                                mode="multiple"
                              >
                                {productDataall &&
                                  productDataall.map(one => (
                                    <Option key={one.pdId} value={one.pdId} datas={one}>
                                      {one.pdName}
                                    </Option>
                                  ))}
                              </Select>
                            )}
                          </FormItem>
                        </Col>
                        <Col span={1}>
                          {index === 0 ? null : (
                            <MinusCircleOutlined
                              style={{ lineHeight: '39px', marginLeft: '-60px', fontSize: 18 }}
                              className="dynamic-delete-button"
                              onClick={() => this.deleteContact(item.id)}
                            />
                          )}
                        </Col>
                      </Row>
                    ))}

                  <FormItem wrapperCol={{ md: { span: 7, offset: 9 } }}>
                    <Button
                      style={{ width: '100%', marginTop: 15, marginBottom: 8, textAlign: 'center' }}
                      type="dashed"
                      icon={<PlusOutlined />}
                      // disabled={this.state.isDisable}
                      onClick={this.addList}
                    >
                      添加分组
                    </Button>
                  </FormItem>
                </div>
              ) : null}

              <div style={{ marginTop: '100px', marginBottom: '30px', textAlign: 'center' }}>
                <Button
                  style={{ marginRight: '30px' }}
                  size="large"
                  onClick={() => router.push('/salemanage/quotation/index')}
                >
                  上一步
                </Button>
                <Button size="large" type="primary" onClick={this.nextStep}>
                  下一步
                </Button>
              </div>
            </Card>
          </Spin>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
